package com.yupi.springbootinit.job.once;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取初始帖子列表
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
// todo 取消注释开启任务 在项目启动时执行一次 执行过一次后就可以把Component注解注释掉
@Component
@Slf4j
public class FetchinitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Override
    public void run(String... args) {
//        1.获取数据
//        要发送的请求
        String json = "{\"pageSize\":12,\"sortOrder\":\"descend\",\"sortField\":\"createTime\",\"tags\":[\"笔记\"],\"current\":1,\"reviewStatus\":1,\"category\":\"文章\",\"hiddenContent\":true}";
//        请求的地址
        String url = "https://api.codefather.cn/api/post/list/page/vo";
        String result = HttpRequest
//                发送post请求
                .post(url)
//                发给后台哪些内容
                .body(json)
//                真正触发执行
                .execute()
//                获取响应的内容
                .body();
//        System.out.println(result);
//       2.返回的是json 我要把它转化成字符串 用Map去接受 什么键值对
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
//            强转
            JSONObject tempRecord = (JSONObject) record;
            Post post = new Post();

            post.setTitle(tempRecord.getStr("title"));
            post.setContent(tempRecord.getStr("plainTextDescription"));
            JSONArray tags =(JSONArray) tempRecord.get("tags");
            List<String> tagList = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(tagList));
            post.setUserId(1L);
            postList.add(post);
        }
//        System.out.println(postList);
//        System.out.println(records);
//        System.out.println(map);
//        3.数据入库 --批量插入
        boolean b = postService.saveBatch(postList);
        if (b){
            log.info("获取初始化帖子列表成功，条数={}，",postList.size());
        }else {
            log.error("获取初始化帖子列表失败");
        }
    }
}
